<template>
  <a-form ref="Form" :model="formData" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
    <a-row>
      <a-col :span="8">
        <a-form-item label="指令编号">
          <a-input v-model:value="formData.zlbh" placeholder="系统按部门自动生成" :read-only="true" :disabled="true" />
        </a-form-item>
      </a-col>
      <a-col :span="8">
        <a-form-item label="来源单位">
          <a-input v-model:value="unitName" placeholder="来源单位" :read-only="true" :disabled="true" />
        </a-form-item>
      </a-col>
      <a-col :span="8">
        <a-form-item label="来源人">
          <a-input v-model:value="nickname" placeholder="来源人" :read-only="true" :disabled="true" />
        </a-form-item>
      </a-col>
      <a-col :span="8">
        <a-form-item label="指令模板">
          <a-button type="primary" @click="chooseTemplate">选择模板指令</a-button>
        </a-form-item>
      </a-col>
      <a-col :span="8">
        <a-form-item label="指令名称" name="zlmc">
          <a-input v-model:value="formData.zlmc" :placeholder="rules.zlmc.message" />
        </a-form-item>
      </a-col>
      <a-col :span="8">
        <a-form-item label="指令级别" name="zljb">
          <a-select
            v-model:value="formData.zljb"
            :options="getEnumList('zljb')"
            :placeholder="rules.zljb.message"
            :getPopupContainer="getContainer"
          />
        </a-form-item>
      </a-col>
      <a-col :span="8">
        <a-form-item label="指令类型" name="zllx">
          <a-select
            v-model:value="formData.zllx"
            :options="getEnumList('zllx')"
            :placeholder="rules.zllx.message"
            :getPopupContainer="getContainer"
          />
        </a-form-item>
      </a-col>
      <a-col :span="8">
        <a-form-item label="选择签收单位" name="dw">
          <a-tree-select
            v-model:value="formData.dw"
            show-search
            multiple
            allowClear
            label-in-value
            treeNodeFilterProp="label"
            placeholder="选择签收单位"
            max-tag-count="responsive"
            :max-tag-text-length="10"
            :fieldNames="{ children: 'nodes', label: 'unit_name', value: 'unit_code' }"
            :tree-data="unitTreeList"
            :tree-checkable="true"
            :getPopupContainer="getContainer"
            :height="300"
            :showCheckedStrategy="showCheckedStrategy"
          />
        </a-form-item>
      </a-col>
      <a-col :span="8">
        <a-form-item label="回复期限">
          <a-date-picker
            v-model:value="formData.hfzq"
            showTime
            valueFormat="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
            :getPopupContainer="getContainer"
          />
        </a-form-item>
      </a-col>
      <a-col :span="24">
        <a-form-item label="指令内容" name="zlnr" :label-col="{ span: 3 }" :wrapper-col="{ span: 21 }">
          <a-textarea v-model:value="formData.zlnr" :rows="5" :placeholder="rules.zlnr.message" />
        </a-form-item>
      </a-col>
      <a-col :span="24">
        <a-form-item label="附件" :label-col="{ span: 3 }" :wrapper-col="{ span: 21 }">
          <uploader
            ref="uploaderRef"
            v-model:urls="formData.fjdz"
            v-model:names="formData.fjmc"
            :max-count="9"
            :col-span="4"
            accept="image,video,audio,doc"
            filePath="zlgl"
          />
        </a-form-item>
      </a-col>
      <a-col v-if="canISendMsg === true && !id" :span="24">
        <a-form-item label="是否需要发送短信提醒" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
          <a-radio-group v-model:value="isSend">
            <a-radio :value="true">是</a-radio>
            <a-radio :value="false">否</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>
</template>

<script>
import { TreeSelect } from 'ant-design-vue';
const showCheckedStrategy = TreeSelect.SHOW_ALL;

import SendMsg from './send-msg.vue';
import Uploader from '@gis/lib/components/Uploader/upload.vue';
import get from 'lodash-es/get.js';
import { useUserInfoStore } from '@gis/lib/pinia/userInfo.js';
import { handleCommonResult, handleFormResult } from '@gis/lib/utils/resolver.js';
import { getEnumList } from '@gis/lib/enums/index.js';
import { instructionAdd, instructionDetails, instructionUpdate, wbdwTree, sendMsgZdyZl } from '@gis/lib/api';
import { getCombineDW, getSplitDW } from '../utils.js';
import { openInstructionTemplateDialog } from '../dialog.js';
import { useTreeDataStore } from '@gis/lib/pinia/treeData.js';

function findDeep(data, predicate) {
  if (!Array.isArray(data) || !data.length) {
    return [];
  }
  return data.reduce((res, item) => {
    if (predicate(item)) {
      res.push(item);
    }
    const people = findDeep(item.people, predicate);
    return res.concat(people);
  }, []);
}

export default {
  name: 'addUpdate',
  components: { Uploader },
  props: {
    id: { type: String, default: '' },
    alarmData: { type: Object, default: undefined },
    getContent: { type: Function, default: undefined },
    canISendMsg: { type: Boolean, default: false },
  },
  data() {
    return {
      isSend: false,
      showCheckedStrategy,
      formData: {},
      rules: {
        zlmc: { required: true, message: '请填写指令名称' },
        zllx: { required: false, message: '请选择指令类型' },
        zljb: { required: true, message: '请选择指令级别' },
        zlnr: { required: true, message: '请填写指令内容' },
        dw: { required: true, message: '请选择签收单位' },
      },
      labelCol: { span: 9 },
      wrapperCol: { span: 15 },
      unitTreeList: [],
    };
  },
  computed: {
    unitName() {
      const userInfo = useUserInfoStore();
      return get(userInfo.userData, 'unitName');
    },
    nickname() {
      const userInfo = useUserInfoStore();
      return get(userInfo.userData, 'nickname');
    },
  },
  created() {
    const unitTree = useTreeDataStore();
    const userInfo = useUserInfoStore();
    this.getQsUnit();

    if (this.id) {
      this.getDetails({ id: this.id });
    } else if (this.alarmData) {
      this.formData.warn_info_id = get(this.alarmData, 'id');
      this.formData.is_warn_info = 1;
      /* 预设内容 */
      if (typeof this.getContent === 'function') {
        this.formData.zlnr = this.getContent(this.alarmData);
      }
    }
  },
  methods: {
    async getQsUnit() {
      const data = handleCommonResult(await wbdwTree());
      this.unitTreeList = data;
    },
    getEnumList,
    chooseTemplate() {
      openInstructionTemplateDialog({
        contentProps: {
          onChange: ({ data }) => {
            this.formData = {
              ...this.formData,
              zlmc: get(data, 'zlmc'),
              zljb: get(data, 'zljb'),
              dw: getCombineDW({
                labels: get(data, 'dwmc'),
                values: get(data, 'dwbm'),
              }),
            };
            this.$refs.Form.clearValidate();
          },
        },
      });
    },
    async onOk() {
      await this.$refs.uploaderRef.checkUploads();
      const valid = await this.$refs.Form.validate();
      if (!valid) return false;
      let dw = get(this.formData, 'dw');
      let params = Object.assign({}, this.formData, {
        zljb: this.formData.zljb ? this.formData.zljb : '一般',
        zllx: this.formData.zllx ? this.formData.zllx : '签收',
        hfzq: this.formData.hfzq ? this.formData.hfzq : '无限',
        ...getSplitDW(dw, { labels: 'qsdwmc', values: 'qsdwbm' }),
      });
      delete params['dw'];
      //预警新增过来的数据
      if (!params.id) {
        params.warn_info_id = get(this.alarmData, 'id') || '';
        params.is_warn_info = params.warn_info_id ? 1 : 0;
      }
      if (!this.id && this.$refs.sendMsgRef) {
        const send = await this.$refs.sendMsgRef.send();
        if (send === false) {
          return;
        }
      }
      const api = this.id ? instructionUpdate : instructionAdd;
      return handleFormResult(await api(params), {
        onOk: async () => {
          const sendMsgParams = {
            unit_code: params.qsdwbm,
            unit_name: params.qsdwmc,
            content: params.zlnr,
          };
          await sendMsgZdyZl(sendMsgParams);
        },
      });
    },
    async getDetails(params) {
      const { instructions = {} } = handleCommonResult(await instructionDetails(params));
      const qsdwbm = get(instructions, 'qsdwbm') || '';
      const qsdwmc = get(instructions, 'qsdwmc') || '';
      const formData = {
        id: instructions.id,
        zlmc: instructions.zlmc,
        zllx: instructions.zllx,
        zljb: instructions.zljb,
        hfzq: instructions.hfzq == '无限' ? null : instructions.hfzq,
        zlnr: instructions.zlnr,
        fjdz: instructions.fjdz,
        fjmc: instructions.fjmc,
        dw: getCombineDW({ values: qsdwbm, labels: qsdwmc }),
      };
      this.formData = formData;
    },
    getContainer(trigger) {
      return document.body;
    },
  },
};
</script>

<style scoped></style>
